/**
 * Project Name:mauto-web
 * File Name:OauthRedirectController.java
 * Package Name:com.inftech.mauto.sys.web.front
 * Date:2016年11月15日下午9:23:41
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.sys.web.front;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.inftech.mauto.common.base.BaseController;
import com.inftech.mauto.common.constant.BusinessConstant;
import com.inftech.mauto.common.constant.SessionConstEnum;
import com.inftech.mauto.core.service.CarService;
import com.inftech.mauto.sys.service.EnterpriseService;
import com.mingsoft.weixin.dao.IWeixinDao;
import com.mingsoft.weixin.dao.IWeixinPeopleDao;
import com.mingsoft.weixin.entity.WeixinEntity;
import com.mingsoft.weixin.entity.WeixinPeopleEntity;
import com.mingsoft.weixin.util.OauthUtils;

/**
 * ClassName:OauthRedirectController <br/>
 * Function: 认证回调地址. <br/>
 * Date: 2016年11月15日 下午9:23:41 <br/>
 * 
 * @author jeno
 * @version
 * @since JDK 1.7
 */
@Controller
@RequestMapping("/oauth")
public class OauthRedirectController extends BaseController {

	/**
	 * 注入车辆业务层
	 */
	@Autowired
	protected CarService carService;

	/**
	 * 注入服务单位业务层
	 */
	@Autowired
	protected EnterpriseService enterpriseService;

	/**
	 * 注入微信持久化层
	 */
	@Autowired
	private IWeixinDao weixinDao;

	/**
	 * 注入微信用户持久化层
	 */
	@Autowired
	private IWeixinPeopleDao weixinPeopleDao;

	/**
	 * 前台主页url
	 */
	@Value("${indexUrlC}")
	private String indexUrlC;

	@RequestMapping(value = "/wxlogin")
	public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mode) throws Exception {

		// 获取用户授权code
		String code = request.getParameter("code");

		// 获取微信信息
		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		OauthUtils oauthUtils = new OauthUtils(weixin.getWeixinAppID(), weixin.getWeixinAppSecret());

		// 已取得code，通过code换取网页授权access_token
		Map<String, Object> accessMap = oauthUtils.getAccessToken(code);
		String openId = String.valueOf(accessMap.get("openid"));

		// 判断用户状态
		Map<String, Object> whereMap = new HashMap<String, Object>();
		whereMap.put("PW_OPEN_ID", openId);
		whereMap.put("PW_PEOPLE_STATE", 1);
		WeixinPeopleEntity weixinPeople = weixinPeopleDao.getEntity(whereMap);
		String params = "{}";
		if (weixinPeople == null) {
			// 未关注该公众号
			LOG.warn("登录失败，openId:" + openId + "未关注公众号");
		} else {
			// 设置cookie
			Byte peopleRole = weixinPeople.getPeopleRole();
			// Cookie cookie = new Cookie(BusinessConstant.COOKIE_NAME,
			// String.valueOf(peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)));
			// cookie.setMaxAge(Integer.MAX_VALUE);
			setSession(request, SessionConstEnum.PEOPLE_SESSION, weixinPeople);
			request.getSession().setMaxInactiveInterval(-1);
//			request.getSession().setMaxInactiveInterval(7 * 24 * 3600);

			Map<String, Object> paramMap = new HashMap<String, Object>();
			boolean peopleRoleb = false;
			if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_S)) {
				peopleRoleb = true;
			}
			paramMap.put("peopleRole", peopleRoleb);
			Map<String, Object> carMap = new HashMap<String, Object>();

			if (peopleRole.equals(BusinessConstant.PEOPLE_ROLE_C)) {
				// 车主角色，获取车辆信息
				carMap = carService.queryCar(weixinPeople.getPeopleId());
				// 获取车主信息
				Map<String, Object> peopleMap = new HashMap<String, Object>();
				peopleMap.put("peopleNickName", weixinPeople.getPeopleUserNickName());
				peopleMap.put("peopleSex", weixinPeople.getPeopleUserSex());
				peopleMap.put("peopleImage", weixinPeople.getWeixinPeopleHeadimgUrl());
				peopleMap.put("peoplePhone", weixinPeople.getPeoplePhone());
				paramMap.put("profile", peopleMap);
			} else {
				// 服务单位角色，获取服务单位信息
				Map<String, Object> enterpriseMap = new HashMap<String, Object>();
				Map<String, Object> enterpriseMap1 = enterpriseService
						.queryEnterprise(weixinPeople.getPeopleEnterpriseId());
				enterpriseMap.put("enterpriseName", enterpriseMap1.get("enterpriseName"));
				enterpriseMap.put("enterpriseTel", enterpriseMap1.get("enterpriseTel"));
				paramMap.put("profile", enterpriseMap);
			}
			paramMap.put("car", carMap);
			params = JSONObject.toJSONString(paramMap);
			LOG.info("登录成功,openId:" + openId);
		}
		params = URLEncoder.encode(params, "utf-8");
		return "redirect:" + indexUrlC + "?res=" + params;
	}
}
